﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SqlServer.Management.Smo;
using Chi.Lib.DBHelper;

public partial class Module_ui_DBTableTree : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
                CreateTBTreeViewNode(this.TreeView1);
    }

    public void CreateTBTreeViewNode(TreeView tree)
    {
        if (Session[SessionKey.TBTreeNode] != null)
        {
            tree.Nodes.Add((TreeNode)Session[SessionKey.TBTreeNode]);
            return;
        }

        Database db = DBHelperSMO.GetDBInstance();
        TreeNode parentNode = new TreeNode();
        parentNode.Value = "Base Table";
        parentNode.Text = string.Format("Table ({0})", db.Tables.Count);
        foreach (Microsoft.SqlServer.Management.Smo.Table tb in db.Tables)
        {
            TreeNode childNode = new TreeNode(tb.Name, tb.ID.ToString());
            foreach (Column col in tb.Columns)
            {
                TreeNode colNode = new TreeNode();
                colNode.Value = col.ID.ToString();
                colNode.Text = string.Format("{0} ({1}{2}({3}), {4})",
                                        col.Name,
                                        col.InPrimaryKey ? "PK, " : "",
                                        col.DataType.Name,
                                        col.DataType.MaximumLength.ToString(),
                                        col.Nullable ? "Null" : "Non Null");

                childNode.ChildNodes.Add(colNode);
            }

            //childNode.SelectAction = TreeNodeSelectAction.Select;
            childNode.NavigateUrl = "~/ShowTableSchemaSMO.aspx?menu=" + parentNode.Text 
                                    + "&tbName=" + childNode.Text
                                    + "&tb=" + childNode.Value
                                    + "&id=" + childNode.Value;
            parentNode.ChildNodes.Add(childNode);
        }

        Session[SessionKey.TBTreeNode] = parentNode;
        tree.Nodes.Add(parentNode);
    }
    protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {
        //TreeView1.SelectedNode.ExpandAll();
        
        //Response.Redirect("ShowTableSchema.aspx?menu=" + TreeView1.SelectedNode.Parent.Text + "&tbName=" + TreeView1.SelectedNode.Text + "&id=" + TreeView1.SelectedNode.Value);
    }
}
